package com.summer.controller;


import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.summer.entity.TbRole;
import com.summer.entity.TbUserinfo;
import com.summer.entity.TbVote;
import com.summer.mapper.TbUserinfoMapper;
import com.summer.mapper.TbVoteMapper;
import com.summer.utils.JwtToken;
import com.summer.utils.MyUtil;
import com.summer.utils.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.summer.vo.aa;
/**
 * <p>
 *  前端控制器
 * </p>
 *https://gitee.com/overcome-odds/voting_system
 * https://gitee.com/tiebing666/voting_system
 * https://gitee.com/goandtryagain/vote_system/tree/master
 * @author summer502
 * @since 2021-03-31
 */
@RestController
@RequestMapping("/tb-vote")
@CrossOrigin
@Transactional
@Api(value = "TbVoteController", description = "活动投票api")

public class TbVoteController {
    Boolean flag;
    MyUtil myUtil = new MyUtil();
    @Autowired (required = false)
    private TbVoteMapper tbVoteMapper;

    /**
     * 添加投票
     * @param activityId
     *
     * @param vote_content
     * @return
     * @throws IOException
     * @throws TokenExpiredException
     */
    @ApiOperation("点击投票按钮投票成功")
    @PostMapping("/web/addTbVote")
    @ResponseBody
    public ResponseEntity addTbVote(@RequestParam(required = false) int activityId,
                                     @RequestParam(required = false) String vote_content,
                                     @RequestHeader String Authorization
                                     ) throws IOException, TokenExpiredException {
            ResponseEntity responseEntity;
            responseEntity = ResponseEntity.ok();
            TbVote tbVote1 = new TbVote();
            String token=Authorization;
            System.out.println(token);
            if (flag = myUtil.judgeToken(token)){
                responseEntity = ResponseEntity.forbidden();
                responseEntity.putDataValue("msg","token不存在或已过期");
                return responseEntity;
            }
            TbUserinfo tbUserinfo = JwtToken.unsign(token, TbUserinfo.class);
            tbVote1.setActivityId(activityId);
            tbVote1.setVoteUserId(tbUserinfo.getUserId());
            tbVote1.setVoteContent(vote_content);

            QueryWrapper<TbVote> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("activity_id", activityId);
            queryWrapper.eq("vote_user_id", tbUserinfo.getUserId());
            List<TbVote> tbVote2 = tbVoteMapper.selectList(queryWrapper);
            if(tbVote2.size()>0){
                responseEntity = ResponseEntity.forbidden();
                responseEntity.putDataValue("msg","已经投过票了不能再投了");
                return responseEntity;
            }
            tbVoteMapper.insert(tbVote1);
            responseEntity.putDataValue("voteId",tbVote1.getVoteId());
            responseEntity.putDataValue("msg","投票成功");
            return responseEntity;
    }

    /**
     * 修改投票信息
     * @param vote_id
     * @param voteContent
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("修改投票信息")
    @PutMapping("/web/updateTbVote")
    @ResponseBody
    public ResponseEntity updateTbVote(@RequestParam(required = true) int vote_id, @RequestParam(required = false) String voteContent,@RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        TbUserinfo users = JwtToken.unsign(token, TbUserinfo.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        } else {
            responseEntity = ResponseEntity.ok();
            TbVote tbVote = tbVoteMapper.selectById(vote_id);
            tbVote.setVoteContent(voteContent);
            tbVoteMapper.updateById(tbVote);
            responseEntity.putDataValue("msg", "教师修改成功");
            return responseEntity;
        }
    }

    /**
     * 根据vote_id查询投票
     * @param vote_id
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据vote_id查询投票")
    @PutMapping("/web/selectByTbVoteId")
    @ResponseBody
    public ResponseEntity selectByTbVoteId(@RequestParam(required = true) Integer vote_id, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        TbUserinfo users = JwtToken.unsign(token, TbUserinfo.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        } else
            responseEntity=ResponseEntity.ok();
            TbVote tbVote = tbVoteMapper.selectById(vote_id);
            responseEntity.putDataValue("tbVote",tbVote);
            return responseEntity;
    }

    /**
     * 查询投票自己的投票记录
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("查询自己的投票记录")
    @PutMapping("/web/selectByTbVote1")
    @ResponseBody
    public ResponseEntity selectByTbVoteId1( @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        TbUserinfo users = JwtToken.unsign(token, TbUserinfo.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        }
        else
            responseEntity=ResponseEntity.ok();
//            TbVote tbVote = tbVoteMapper.selectById(users.getUserId());
//            responseEntity.putDataValue("tbVote",tbVote);
            QueryWrapper<TbVote> wrapper = new QueryWrapper<>();
            wrapper.eq("vote_user_id",users.getUserId());
            List<TbVote> list=tbVoteMapper.selectList(wrapper);
            responseEntity.putDataValue("list",list);
            return responseEntity;
    }

//    /**
//     * 根据id删除教师信息
//     * @param teacher_id
//     * @param Authorization
//     * @return
//     * @throws IOException
//     */
//    @ApiOperation("根据id删除教师信息")
//    @PutMapping("/web/deleteTeacher")
//    @ResponseBody
//    public ResponseEntity deleteTeacher(@RequestParam(required = true) Integer teacher_id,@RequestHeader String Authorization)throws IOException{
//        ResponseEntity responseEntity;
//        String token=Authorization;
//        if(flag=myUtil.judgeToken(token)){
//            responseEntity=ResponseEntity.forbidden();
//            responseEntity.putDataValue("msg","token不存在或已过期");
//            return responseEntity;
//        }
//        User users=JwtToken.unsign(token,User.class);
//        if(users==null){
//            responseEntity=ResponseEntity.notFound();
//            responseEntity.putDataValue("msg","用户不存在");
//            return responseEntity;
//        }else if(users.getUser_role()==2) {
//            TbVote teacher = tbVoteMapper.selectById(teacher_id);
//            if(teacher!=null){
//                int is_delete = 1;
//                teacher.setIs_delete(is_delete);
//                tbVoteMapper.updateById(teacher);
//                responseEntity=ResponseEntity.ok();
//                responseEntity.putDataValue("msg","删除成功");
//                return responseEntity;
//            }
//        }
//        responseEntity=ResponseEntity.unauthorized();
//        responseEntity.putDataValue("msg","没有权限");
//        return responseEntity;
//    }
//    /**
//     * 教师列表
//     * @param Authorization
//     * @param response
//     * @return
//     * @throws IOException
//     */
    @ApiOperation("活动管理者组织协会(根据activity_id查看的投票列表)")
    @PostMapping("/web/TbVoteList")
    @ResponseBody
    public ResponseEntity TbVoteList(@RequestHeader String Authorization,
                                       @RequestParam(required = true)int activity_id,
                                       HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        TbUserinfo user = JwtToken.unsign(token, TbUserinfo.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        if (user.getRoleId()!=1||user.getRoleId()!=2){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","权限错误");
            responseData.putDataValue("timestamp",myUtil.getTime());
            return responseData;
        }
        QueryWrapper<TbVote> wrapper = new QueryWrapper<>();
        wrapper.eq("activity_id",activity_id);

        List<TbVote> list = tbVoteMapper.selectList(wrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("user",list);
        responseData.putDataValue("msg","成功");
        return responseData;
    }
    /**
     * 查询某个活动的分组统计投票数量
     * https://www.cnblogs.com/liuyangfirst/p/9739063.html
     */
    @ApiOperation("查询某个活动的分组统计投票数量")
    @GetMapping("/web/count")
    @ResponseBody
    public ResponseEntity count(@RequestParam(required = true)int activity_id) throws IOException {
        ResponseEntity responseData;
        int is_delete = 0;
        //参考链接：https://blog.csdn.net/weixin_44339331/article/details/105232544?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-6.control&dist_request_id=1328769.28872.16174502930524899&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-6.control
        List<HashMap<String, Object>> list = tbVoteMapper.getDepNumMap(activity_id);
        Map<String, Integer> map = new HashMap<>();
        if (list != null && !list.isEmpty()) {
            for (HashMap<String, Object> hashMap : list) {
                String key = null;
                Integer value = null;
                for (Map.Entry<String, Object> entry : hashMap.entrySet()) {
                    if ("key".equals(entry.getKey())) {
                        key = (String) entry.getValue();
                    } else if ("value".equals(entry.getKey())) {
                        //我需要的是int型所以做了如下转换，实际上返回的object应为Long。
                        value = ((Long)entry.getValue()).intValue();
                    }
                }
                map.put(key, value);
            }
        }

//        QueryWrapper<TbVote> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("is_delete", is_delete);
//        queryWrapper.eq("activity_id", activity_id);
//        queryWrapper.select("vote_content,count(*) count");
//        queryWrapper.groupBy("vote_content");
//        System.out.println(queryWrapper);
//        System.out.println("111111-----");
////        int  count =tbVoteMapper.selectCount(queryWrapper);
//        List<TbVote> list=tbVoteMapper.selectList(queryWrapper);
//        for (TbVote tbVote : list) {
//            System.out.println(tbVote);
//        }
//        System.out.println("-------");
//        System.out.println(list);
//        //HashMap<String,String> hashMap=new HashMap<>();
//        //hashMap.put("vote_content",list.add());
//        Object json = JSONObject.toJSON(list);
//        Gson gson = new Gson();
//        gson.toJson(list);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("list", map);
        return responseData;
    }


}
